package org.linlinjava.litemall.db.service;

import java.time.LocalDateTime;
import java.util.List;

import javax.annotation.Resource;

import org.linlinjava.litemall.db.dao.LitemallSettlementMapper;
import org.linlinjava.litemall.db.domain.LitemallSettlement;
import org.linlinjava.litemall.db.domain.LitemallSettlementExample;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

 

@Service
public class LitemallSettlementService {
	
    @Resource
    private LitemallSettlementMapper settlementMapper;
    
    public LitemallSettlement findById(Integer id) {
    	return settlementMapper.selectByPrimaryKey(id);
    }

    public void add(LitemallSettlement settlement) {
    	settlement.setAddTime(LocalDateTime.now());
        settlementMapper.insertSelective(settlement);
    }
    
    public void update(LitemallSettlement settlement) {
    	settlementMapper.updateByPrimaryKeySelective(settlement);
    }

    public List<LitemallSettlement> querySelective(Integer shopId, Integer userId, String name, Integer page, Integer size, String sort, String order) {
        LitemallSettlementExample example = new LitemallSettlementExample();
        LitemallSettlementExample.Criteria criteria = example.createCriteria();

        if (shopId != null) {
        	criteria.andShopIdEqualTo(shopId);
        }
        
        if (userId != null) {
        	criteria.andUserIdEqualTo(userId);
        }
        
        if (!StringUtils.isEmpty(name)) {
            criteria.andUserNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        //PageHelper.startPage(page, size);
        return settlementMapper.selectByExample(example);
    }
    
    /**
     * 查询该机器的最新的交接记录
     * @param deviceNo
     * @return
     */
    public LitemallSettlement getLatest(String deviceNo) {
    	LitemallSettlementExample example = new LitemallSettlementExample();
    	example.or().andDeviceNoEqualTo(deviceNo).andDeletedEqualTo(false);
    	example.setOrderByClause("add_time desc");
    	List<LitemallSettlement> list = settlementMapper.selectByExample(example);
    	if(CollectionUtils.isEmpty(list)) {
    		return null;
    	}else {
    		return list.get(0);
    	}
    }
}
